package com.gcloud.mesh.dcs.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.gcloud.mesh.header.msg.dcs.*;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.MyBusinessException;
import org.jeecg.common.exception.ParamException;
import org.jeecg.common.util.LogUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.gcloud.framework.db.PageResult;
import com.gcloud.mesh.asset.dao.CloudResourceConfigDao;
import com.gcloud.mesh.asset.dao.CloudResourceDao;
import com.gcloud.mesh.asset.dao.DatacenterDao;
import com.gcloud.mesh.asset.entity.CloudResourceConfigEntity;
import com.gcloud.mesh.asset.entity.CloudResourceEntity;
import com.gcloud.mesh.asset.entity.DatacenterEntity;
import com.gcloud.mesh.asset.enums.CloudResourceType;
import com.gcloud.mesh.asset.enums.MockType;
import com.gcloud.mesh.dcs.dao.AppDao;
import com.gcloud.mesh.dcs.dao.AppInstanceDao;
import com.gcloud.mesh.dcs.dao.SchedulerConfigDao;
import com.gcloud.mesh.dcs.entity.AppEntity;
import com.gcloud.mesh.dcs.entity.AppInstanceEntity;
import com.gcloud.mesh.dcs.entity.SchedulerConfigEntity;
import com.gcloud.mesh.dcs.entity.SchedulerJobEntity;
import com.gcloud.mesh.dcs.enums.AppType;
import com.gcloud.mesh.dcs.enums.SchedulerJobStatus;
import com.gcloud.mesh.dcs.strategy.NameSpaceFilterConfig;
import com.gcloud.mesh.dcs.strategy.QueryInstanceContext;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.header.enums.AuthorityResourceClassification;
import com.gcloud.mesh.header.enums.ResourceSourceType;
import com.gcloud.mesh.header.enums.SchedulerTriggerPolicy;
import com.gcloud.mesh.header.exception.AppErrorCode;
import com.gcloud.mesh.header.exception.BaseException;
import com.gcloud.mesh.header.vo.dcs.AppDetailItemVo;
import com.gcloud.mesh.header.vo.dcs.AppInstanceType;
import com.gcloud.mesh.header.vo.dcs.AppInstanceVo;
import com.gcloud.mesh.header.vo.dcs.AppItemVo;
import com.gcloud.mesh.header.vo.dcs.AppVo;
import com.gcloud.mesh.header.vo.dcs.AuthorityVo;
import com.gcloud.mesh.header.vo.dcs.MockAppVo;
import com.gcloud.mesh.header.vo.dcs.VmItemVo;
import com.gcloud.mesh.redis.MockRedis;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.gce.GcePageReply;
import com.gcloud.mesh.sdk.gce.NamespaceVo;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.supplier.enums.SystemType;
import com.gcloud.mesh.threads.ThreadManager;
import com.gcloud.mesh.utils.TimestampUtil;
import com.google.api.client.util.Lists;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AppService {

	@Autowired
	private MockRedis<MockAppVo> mockRedis;

	@Autowired
	private AppDao appDao;

	@Autowired
	private AppInstanceDao appInstanceDao;

	@Autowired
	private AppProfileService appProfileService;

	@Autowired
	private DatacenterDao datacenterDao;

	@Autowired
	private SchedulerAdviceService schedulerAdviceService;

	@Autowired
	private SchedulerConfigDao schedulerConfigDao;

	@Autowired
	private CloudResourceDao cloudResourceDao;

	@Autowired
	private CloudResourceConfigDao cloudResourceConfigDao;

	@Autowired
	private SupplierDao supplierDao;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private QueryInstanceContext queryInstanceContext;

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private NameSpaceFilterConfig namespaceConfig;

	public String create(CreateAppMsg msg) {
		log.info("[{}][App] 开始创建App：{}", msg.getMsgId(), msg);
		List<AppEntity> apps = appDao.findByProperty("name", msg.getName());
		if(apps!=null && !apps.isEmpty()) throw new ParamException(AppErrorCode.NAME_DUPLICATE);
		AppEntity entity = new AppEntity();
		// TODO mo
		CloudResourceEntity cloudResourceEntity = cloudResourceDao.findOneByProperty("id", msg.getCloudResourceId());
		if (cloudResourceEntity == null) throw new MyBusinessException("没找到相应的云平台资源");
		else if (cloudResourceEntity.getType() == CloudResourceType.HUAWEI.getType()
				|| cloudResourceEntity.getType() == CloudResourceType.ALI.getType()
				|| cloudResourceEntity.getType() == CloudResourceType.K8S.getType()) {
		} else throw new MyBusinessException("云平台资源类型不正确");
		entity.setId(UUID.randomUUID().toString());
		entity.setName(msg.getName());
		entity.setCreateTime(new Date());
		entity.setCloudResourceId(msg.getCloudResourceId());
		entity.setType(cloudResourceEntity.getType());
		entity.setFrom(ResourceSourceType.MANUAL.getName());
		entity.setDeleted(false);
		appDao.save(entity);
		log.info("[{}][App] 创建App成功", msg.getMsgId());
		// 初始化应用画像建议
		ThreadManager.submit(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					appProfileService.initAppProfile(entity.getId());
				} catch (Exception e) {
					log.info("[{}][App] 初始化应用画像建议异常:{}", msg.getMsgId(), e.getMessage());
				}
			}
		});
		List<AppInstanceEntity> instances = new ArrayList<AppInstanceEntity>();
		if (msg.getInstances() != null) {
			for (AppInstance instance : msg.getInstances()) {
				AppInstanceEntity aientity = new AppInstanceEntity();
				aientity.setAppId(entity.getId());
				aientity.setInstanceId(instance.getInstanceId());
				aientity.setName(instance.getInstanceName());
				aientity.setCreateTime(new Date());
				instances.add(aientity);
			}
		}
		appInstanceDao.saveBatch(instances);
		// TODO 新增模拟数据
		// mockRedis.set(entity.getId(), MockType.APP, entity);

		return entity.getId();
	}


	public void update(UpdateAppMsg msg) {
		log.info("[{}][App] 开始更新App：id={}, name={}", msg.getMsgId(), msg.getAppId(), msg.getName());
		AppEntity app = appDao.getById(msg.getAppId());
		if (app == null) {
			log.error("[{}][App] 更新App失败，App不存在", msg.getMsgId());
			throw new ParamException(AppErrorCode.APP_NOT_EXIST);
		}
		if (!app.getName().equals(msg.getName())) {
			List<AppEntity> appdbs = appDao.findByProperty("name", msg.getName());
			for (AppEntity appdb : appdbs) {
				if (appdb != null && appdb.getName() != null && appdb.getName().equals(msg.getName())) {
					log.error("[{}][App] 更新App失败，名字重复", msg.getMsgId());
					throw new ParamException(AppErrorCode.NAME_DUPLICATE);
				}
			}
		}
		if (app.getFrom() == ResourceSourceType.SYNC.getName()) {
			log.error("[{}][App] 更新App失败，同步资源不允许更新", msg.getMsgId());
			throw new ParamException(AppErrorCode.APP_SYNC_NOT_UPDATE);
		}
		boolean updated = false;
		if (!StringUtils.equals(app.getName(), msg.getName())) {
			String oldName = app.getName();
			app.setName(msg.getName());
			updated = true;
		}
		if (msg.getType() != null) {
			app.setType(msg.getType());
			updated = true;
		}
		if (updated) {
			appDao.update(app);
			log.info("[{}][App] 更新App成功：name={} -> {}", msg.getMsgId(), app.getName(), msg.getName());
		}

		// TODO 修改模拟数据
		// mockRedis.set(app.getId(), MockType.APP, app);
	}

	public PageResult<AppItemVo> page(PageAppMsg msg) {
		Map<String, String> datacenterMap = null;
		if(StringUtils.isNotBlank(msg.getDatacenterId())) {
			DatacenterEntity entity = datacenterDao.getById(msg.getDatacenterId());
			datacenterMap = new HashMap<>();
			datacenterMap.put(entity.getId(), entity.getName());
		}else {
			datacenterMap = datacenterDao.findAll().stream().collect(Collectors.toMap(DatacenterEntity::getId, s -> s.getName()));
		}
		PageResult<AppItemVo> page = appDao.page(msg.getName(), msg.getType(), msg.getCloudResourceId(),
				msg.getPageNo(), msg.getPageSize(), AppItemVo.class, msg.getDatacenterId());
		if (page.getList() != null && datacenterMap != null) {
			for (AppItemVo av : page.getList()) {
				//av.setTypeName(AppType.getByType(av.getType()).getName());
				av.setDatacenterName(datacenterMap.get(av.getDatacenterId()));
			}
		}

		return page;
	}

	public AppVo checkAndGet(String appId) throws BaseException {
		AppVo app = appDao.getVoById(appId);
		if (app == null) {
			throw new ParamException(AppErrorCode.APP_NOT_EXIST);
		}
		return app;
	}

	public int count() throws BaseException {
		return appDao.count();
	}

	public int conutInstance(String datacenterId) throws BaseException {
		return appInstanceDao.countByDatacenter(datacenterId);
	}

	public String myUpdateSchedulerConfig(MyUpdateAppSchedulerConfigMsg msg) {
		DatacenterEntity datacenter = datacenterDao.getById(msg.getDatacenterId());
		if (datacenter == null) {
			throw new ParamException(AppErrorCode.DATACENTERID_NOT_EXIST);
		}
		// 删除原来的
		jdbcTemplate.update("delete from dcs_scheduler_configs where datacenter_id = ?", msg.getDatacenterId());
		// 新增
		List<SchedulerConfigEntity> list = msg.getSchedulerConfigList().stream().map(s -> {
			SchedulerConfigEntity sce = new SchedulerConfigEntity();
			BeanUtils.copyProperties(s, sce);
			sce.setDatacenterId(msg.getDatacenterId());
			sce.setUpdateTime(new Date());
			return sce;
		}).collect(Collectors.toList());
		schedulerConfigDao.saveBatch(list);
		return msg.getDatacenterId();
	}

	public String updateSchedulerConfig(UpdateAppSchedulerConfigMsg msg) {

		// if (msg.getThresholdKey() != null) {
		// SchedulerTriggerPolicy policy =
		// SchedulerTriggerPolicy.getByMeter(msg.getThresholdKey());
		// if (policy == null) {
		// throw new BaseException(null, "该调度触发策略不支持");
		// }
		// if (policy == SchedulerTriggerPolicy.CLUSTER_CPU_CORES
		// || policy == SchedulerTriggerPolicy.CLUSTER_MEM_SPACE) {
		// if (msg.getThresholdValue() > 100) {
		// throw new ParamException("最大值不能大于100");
		// }
		// }
		// }

		DatacenterEntity datacenter = datacenterDao.getById(msg.getDatacenterId());
		if (datacenter == null) {
			throw new ParamException(AppErrorCode.DATACENTERID_NOT_EXIST);
		}

		SchedulerConfigEntity schedulerConfig = schedulerConfigDao.findUniqueByProperty("datacenterId",
				datacenter.getId());
		if (schedulerConfig != null) {
			schedulerConfig.setThresholdKey(msg.getThresholdKey());
			schedulerConfig.setThresholdOperation(msg.getThresholdOperation());
			schedulerConfig.setThresholdValue(msg.getThresholdValue());
			schedulerConfig.setUpdateTime(new Date());
			schedulerConfigDao.update(schedulerConfig);
		} else {
			schedulerConfig = new SchedulerConfigEntity();
			schedulerConfig.setId(UUID.randomUUID().toString());
			schedulerConfig.setDatacenterId(msg.getDatacenterId());
			schedulerConfig.setThresholdKey(msg.getThresholdKey());
			schedulerConfig.setThresholdOperation(msg.getThresholdOperation());
			schedulerConfig.setThresholdValue(msg.getThresholdValue());
			schedulerConfig.setUpdateTime(new Date());
			schedulerConfigDao.save(schedulerConfig);
		}
		return schedulerConfig.getId();

		// 清空调度任务
		// List<SchedulerJobEntity> schedulerJobs =
		// schedulerJobDao.findByProperty("app_id", app.getId());
		// if (schedulerJobs != null) {
		// for (SchedulerJobEntity schedulerJob : schedulerJobs) {
		// schedulerJobDao.deleteById(schedulerJob.getId());
		// }
		// }

		//
		// // 手动触发调度模式
		// if
		// (TriggerStrategyType.MANUAL.getValue().equals(msg.getTriggerStrategy()))
		// {
		// DatacenterEntity dstDc =
		// datacenterDao.getById(msg.getDatacenterId());
		// if (dstDc == null) {
		// throw new BaseException("目标数据中心不存在");
		// }
		//
		// // 直接创建调度任务
		// SchedulerJobEntity schedulerJob = new SchedulerJobEntity();
		// schedulerJob.setAppId(app.getId());
		// schedulerJob.setBeginTime(new Date());
		// schedulerJob.setId(UUID.randomUUID().toString());
		// schedulerJob.setStatus(SchedulerJobStatus.READY.getValue());
		// // schedulerJob.setSrcDatacenterId(app.getDatacenterId());
		// schedulerJob.setDstDatacenterId(dstDc.getId());
		// schedulerJobDao.save(schedulerJob);
		// } else if
		// (TriggerStrategyType.AUTO.getValue().equals(msg.getTriggerStrategy()))
		// {
		// if (msg.getThreshold() != null) {
		// for (SchedulerThresholdVo stv : msg.getThreshold()) {
		// SchedulerThresholdEntity ste = new SchedulerThresholdEntity();
		// ste.setId(UUID.randomUUID().toString());
		// ste.setKey(stv.getKey());
		// ste.setOperation(stv.getOperation());
		// ste.setValue(stv.getValue());
		// ste.setSchedulerConfigId(schedulerConfig.getId());
		// schedulerThresholdDao.save(ste);
		// }
		// }
		//
		// }

	}

	// 从gce服务上拉取app应用
	public String syncGceApp(SyncAppMsg syncAppMsg) {
		GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
		List<AuthorityVo> authorities = appDao.listAuthority(AuthorityResourceClassification.APP.getName());
		List<String> filterAuthorities = authorities.stream().filter(s -> !s.getEnabled()).map(s -> s.getId())
				.collect(Collectors.toList());
		String templateAll = "应用资源同步成功!";
		String templateNone = "应用资源同步失败，请开启资源权限!";
		if (filterAuthorities.size() == 1) {
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			LogUtil.log(request, templateNone);
			throw new BaseException("000000", templateNone);
		}
		CloudResourceEntity cloudResourceEntity = cloudResourceDao.findOneByProperty("id",
				syncAppMsg.getCloudResourceId());
		if (cloudResourceEntity == null)
			throw new MyBusinessException("请选择正确的云平台资源");

		// 判断是否有配置同步
		SupplierEntity supplierEntity = supplierDao.findOneByProperty("datacenterId",
				cloudResourceEntity.getDatacenterId());
		if (supplierEntity == null)
			throw new MyBusinessException("请先在数据中心上关联同步的集群");
		if (CloudResourceType.K8S.getType() == cloudResourceEntity.getType()) {
			String[] appIds = syncAppMsg.getAppIds();
			if (appIds == null || appIds.length == 0)
				throw new MyBusinessException("应用ID不能为空");
			GcePageReply<NamespaceVo> namespaceVoGcePageReply = gceSDK.pageNamespace(supplierEntity.getClusterId(), 1,
					Integer.MAX_VALUE);
			List<NamespaceVo> data = namespaceVoGcePageReply.getData();
			if (data == null || data.isEmpty())
				throw new MyBusinessException("没有需要同步的应用");
			List<NamespaceVo> syncList = data.stream().filter(namespaceVo -> Arrays.stream(syncAppMsg.getAppIds())
					.anyMatch(id -> namespaceVo.getId().equalsIgnoreCase(id))).collect(Collectors.toList());
			if (syncList == null || syncList.isEmpty())
				throw new MyBusinessException("没有需要同步的应用");
			// 需要同步的app
			Map<String, AppEntity> appMap = new HashMap<String, AppEntity>();
			List<AppEntity> list = appDao.findAll();
			for (AppEntity r : list) {
				appMap.put(r.getId(), r);
			}
			for (NamespaceVo r : syncList) {
				boolean result = appDao.isSyncProcess(r.getId());
				if (result)
					continue;
				if (appMap.containsKey(r.getId())) {
					AppEntity app = appMap.get(r.getId());
					app.setDeleted(false);
					app.setCreateTime(TimestampUtil.strToDate(r.getCreateAt(), "yyyy-MM-dd HH:mm:ss"));
					app.setCloudResourceId(syncAppMsg.getCloudResourceId());
					app.setFrom(ResourceSourceType.SYNC.getName());
					app.setType(0); // 有状态1？无状态0
					appDao.update(app);
				} else {
					AppEntity app = new AppEntity();
					BeanUtils.copyProperties(r, app);
					app.setCloudResourceId(syncAppMsg.getCloudResourceId());
					app.setFrom(ResourceSourceType.SYNC.getName());
					app.setCreateTime(TimestampUtil.strToDate(r.getCreateAt(), "yyyy-MM-dd HH:mm:ss"));
					app.setDeleted(false);
					app.setType(0); // 有状态1无状态0
					appDao.save(app);
					// 初始化应用画像建议
					ThreadManager.submit(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							try {
								appProfileService.initAppProfile(app.getId());
							} catch (Exception e) {
								log.info("[{}][App] 初始化应用画像建议异常:{}", app.getId(), e.getMessage());
							}
						}
					});
				}

			}

		} else if (CloudResourceType.HUAWEI.getType() == cloudResourceEntity.getType()
				|| CloudResourceType.ALI.getType() == cloudResourceEntity.getType()) {
			String[] appIds = syncAppMsg.getAppIds();
			if (appIds == null || appIds.length == 0)
				throw new MyBusinessException("应用ID不能为空");

			List<AppEntity> appEntities = queryInstanceContext.queryServerList(
					SystemType.getSystemTypeByName(supplierEntity.getType()).getName(),
					supplierEntity.getDatacenterId());
			if (appEntities == null || appEntities.isEmpty())
				throw new MyBusinessException("没有需要同步的应用");
			List<AppEntity> syncList = appEntities.stream()
					.filter(app -> Arrays.stream(appIds).anyMatch(id -> app.getId().equalsIgnoreCase(id)))
					.collect(Collectors.toList());

			if (syncList != null && !syncList.isEmpty()) {

				for (AppEntity appEntity : syncList) {

					boolean result = appDao.isSyncProcess(appEntity.getId());
					if (result)
						continue;
					// if(redisUtil.get(String.format("job:transfer:%s",
					// appEntity.getId()))!=null) continue;

					AppEntity app = appDao.findOneByProperty("id", appEntity.getId(), AppEntity.class);
					if (app == null) {
						app = new AppEntity();
						app.setType(1);
						app.setName(appEntity.getName());
						app.setFrom("sync");
						app.setDeleted(false);
						app.setId(appEntity.getId());
						app.setCreateTime(new Date());
						app.setCloudResourceId(cloudResourceEntity.getId());
						appDao.save(app);
					} else {
						app.setName(appEntity.getName());
						app.setId(appEntity.getId());
						app.setCloudResourceId(cloudResourceEntity.getId());
						appDao.update(app);
					}
				}

			}

		} else {
			throw new MyBusinessException("请选择正确的APP同步类型");
		}

		return templateAll;
	}

	public String sync() {

		List<AuthorityVo> authorities = appDao.listAuthority(AuthorityResourceClassification.APP.getName());
		List<String> filterAuthorities = authorities.stream().filter(s -> !s.getEnabled()).map(s -> s.getId())
				.collect(Collectors.toList());

		String templateAll = "应用资源同步成功!";
		String templateNone = "应用资源同步失败，请开启资源权限!";

		// 获取对应云资源假数据
		List<MockAppVo> res = mockRedis.getByType(MockType.APP);
		if (res != null) {
			Map<String, AppEntity> appMap = new HashMap<String, AppEntity>();
			List<AppEntity> list = appDao.findAll();
			for (AppEntity r : list) {
				appMap.put(r.getId(), r);
			}

			for (MockAppVo r : res) {
				if (appMap.containsKey(r.getId())) {
					List<String> updates = new ArrayList<String>();
					AppEntity app = appMap.get(r.getId());
					updates.add("deleted");
					app.setDeleted(false);
					appDao.update(app, updates);
				} else {
					AppEntity app = new AppEntity();
					BeanUtils.copyProperties(r, app);
					app.setFrom(ResourceSourceType.SYNC.getName());
					app.setCreateTime(TimestampUtil.strToDate(r.getCreateTime(), "yyyy/MM/dd HH:mm:ss"));
					app.setDeleted(false);
					appDao.save(app);
					// 初始化应用画像建议
					ThreadManager.submit(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							try {
								appProfileService.initAppProfile(app.getId());
							} catch (Exception e) {
								log.info("[{}][App] 初始化应用画像建议异常:{}", app.getId(), e.getMessage());
							}
						}
					});
				}

			}
		}

		if (filterAuthorities.size() == 1) {
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			LogUtil.log(request, templateNone);
			throw new BaseException("000000", templateNone);
		}
		return templateAll;
	}

	public List<AppInstanceType> queryAppList(String cloudResourceId, String appId) {
		// SupplierEntity supplierEntity =
		// supplierDao.findOneByProperty("datacenter_id", datacenterId);
		// if(supplierEntity==null) return null;
		// if(SystemType.K8S.getName().equalsIgnoreCase(supplierEntity.getType())){
		// GceSDK gceSDK = SpringContextUtils.getBean(GceSDK.class);
		// try {
		// GcePageReply<NamespaceVo> namespaceList =
		// gceSDK.pageNamespace(supplierEntity.getClusterId(), 1,
		// Integer.MAX_VALUE);
		// return namespaceList.getData().stream().map(n -> new
		// AppEntity().setName(n.getName()).setId(n.getId())).collect(Collectors.toList());
		// }catch (Exception e){
		// return Lists.newArrayList();
		// }
		// }else{
		// return
		// serverMigrationStrategyContext.queryServerList(supplierEntity.getType(),datacenterId);
		// }
		List<String> appInstances = new ArrayList<>();
		if(StringUtils.isNotBlank(appId)) {
			List<AppInstanceEntity> instances = appInstanceDao.findByProperty("appId", appId);
			for(AppInstanceEntity instance : instances) {
				appInstances.add(instance.getInstanceId());
			}
		}
		// zhangdp 这 里换成查询云资源的配置
		CloudResourceConfigEntity cloudConfig = cloudResourceConfigDao.findOneByProperty("cloud_resource_id",
				cloudResourceId);
		if (cloudConfig == null)
			return null;
		List<AppEntity> appinstances = Lists.newArrayList();
		List<AppInstanceType> resList = Lists.newArrayList();
		if (cloudConfig.getType().equals(SystemType.K8S.getNo())) {
			GceSDK gceSDK = SpringContextUtils.getBean(GceSDK.class);
			try {
				GcePageReply<NamespaceVo> namespaceList = gceSDK.pageNamespace(cloudConfig.getClusterId(), 1,
						Integer.MAX_VALUE);
				appinstances =  namespaceList.getData().stream().map(n -> new AppEntity().setName(n.getName()).setId(n.getId()))
						.collect(Collectors.toList());
				Iterator<AppEntity> it = appinstances.iterator();
				while(it.hasNext()) {
					AppEntity en = it.next();
					if(namespaceConfig.contains(en.getName())) {
						it.remove();
					}
				}
			} catch (Exception e) {
				appinstances = Lists.newArrayList();
			}
		} else {
			SystemType type = SystemType.getSystemTypeByNo(cloudConfig.getType());
			appinstances = queryInstanceContext.queryServerList(type.getName(), cloudResourceId);
		}
		//查询已经插入库的
		List<AppInstanceEntity> instances = appInstanceDao.findAll();
		List<String> hasChoose = new ArrayList<>();
		if(instances != null && !instances.isEmpty()) {
			for(AppInstanceEntity instance : instances) {
				hasChoose.add(instance.getInstanceId());
			}
		}
		Iterator<AppEntity> it = appinstances.iterator();
		while(it.hasNext()) {
			AppEntity appInstance = it.next();
			AppInstanceType type  = new AppInstanceType();
			BeanUtils.copyProperties(appInstance, type);
			if(hasChoose.contains(appInstance.getId())) {
				continue;
			}else {
				type.setDisable(false);
			}
			if(appInstances.contains(appInstance.getId())) {
				type.setSelected(true);
			}else {
				type.setSelected(false);
			}
			resList.add(type);
		}
		return resList;
	}

	public AppDetailItemVo detail(String appId) {
		//查出所有的cloud_resource
		Map<String, String> idNameMap = new HashMap<>();
		List<CloudResourceEntity> alls = cloudResourceDao.findAll();
		if(alls != null) {
			for(CloudResourceEntity entity : alls) {
				idNameMap.put(entity.getId(), entity.getName());
			}
		}
		AppItemVo appvo = appDao.getByAppId(appId);
		List<AppInstanceVo> instances = appInstanceDao.listInstancesByAppId(appId);
		AppDetailItemVo vo = new AppDetailItemVo();
		BeanUtils.copyProperties(appvo, vo);
		vo.setTypeName(SystemType.getSystemTypeByNo(vo.getType()).getName());
		for (AppInstanceVo instancevo : instances) {
			instancevo.setStatusName("正常");
			SchedulerJobStatus status = SchedulerJobStatus.getByValue(instancevo.getStatus());
			if (status != null && !status.equals(SchedulerJobStatus.SUCCESS)) {
				instancevo.setStatusName("迁移" + status.getName());
			}
			if(status != null && status.equals(SchedulerJobStatus.SUCCESS)) {
				instancevo.setResourceName(idNameMap.get(instancevo.getDstCloudResourceId()));
				instancevo.setResourceId(instancevo.getDstCloudResourceId());
			}
			if (instancevo.getResourceName() == null) {
				instancevo.setResourceName(appvo.getCloudResourceName());
				instancevo.setResourceId(appvo.getCloudResourceId());
			}
		}
		vo.setInstances(instances);
		return vo;
	}

	public PageResult<VmItemVo> vmpage(@Valid PageVmMsg msg) {
		Map<String, String> datacenterMap = null;
		if(StringUtils.isNotBlank(msg.getDatacenterId())) {
			DatacenterEntity entity = datacenterDao.getById(msg.getDatacenterId());
			datacenterMap = new HashMap<>();
			datacenterMap.put(entity.getId(), entity.getName());
		}else {
			datacenterMap = datacenterDao.findAll().stream().collect(Collectors.toMap(DatacenterEntity::getId, s -> s.getName()));
		}
		PageResult<VmItemVo> page = appInstanceDao.vmpage(msg.getName(), msg.getType(), msg.getCloudResourceId(),
				msg.getPageNo(), msg.getPageSize(),msg.getDatacenterId(),  VmItemVo.class);
		if (page.getList() != null && datacenterMap != null) {
			for (VmItemVo av : page.getList()) {
				av.setTypeName(CloudResourceType.getByType(av.getResourceType()).getName());
				av.setDatacenterName(datacenterMap.get(av.getDatacenterId()));
			}
		}

		return page;
	}

	public PageResult<AppInstanceVo> instancePage(@Valid PageInstanceMsg msg) {
		Map<String, String> datacenterMap = datacenterDao.findAll().stream().collect(Collectors.toMap(DatacenterEntity::getId, s -> s.getName()));
		Map<String, String> resourceMap = cloudResourceDao.findAll().stream().collect(Collectors.toMap(CloudResourceEntity::getId, s -> s.getName()));
		PageResult<AppInstanceVo> page = appInstanceDao.instancePage(msg);
		List<AppInstanceVo> instances = page.getList();
		for (AppInstanceVo instancevo : instances) {
			instancevo.setStatusName("正常");
			instancevo.setStatus(instancevo.getStatus() == null ? 3: instancevo.getStatus());
			SchedulerJobStatus status = SchedulerJobStatus.getByValue(instancevo.getStatus());
			if (status != null && !status.equals(SchedulerJobStatus.SUCCESS)) {
				instancevo.setStatusName("迁移" + status.getName());
			}
			if(status != null && status.equals(SchedulerJobStatus.SUCCESS)) {
				instancevo.setResourceName(resourceMap.get(instancevo.getDstCloudResourceId()));
				instancevo.setDatacenterName(datacenterMap.get(instancevo.getDstDatacenterId()));
				instancevo.setResourceId(instancevo.getDstCloudResourceId());
				instancevo.setDatacenterId(instancevo.getDstDatacenterId());
			}
			if (instancevo.getResourceName() == null) {
				instancevo.setResourceName(resourceMap.get(instancevo.getSrcCloudResourceId()));
				instancevo.setDatacenterName(datacenterMap.get(instancevo.getSrcDatacenterId()));
				instancevo.setResourceId(instancevo.getSrcCloudResourceId());
				instancevo.setDatacenterId(instancevo.getSrcDatacenterId());
			}
		}
		return page;
	}
	
}
